package com.dfch.auto.appium.utils;

import com.dfch.auto.appium.ui.TipWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ADBUtil extends EnvUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ADBUtil.class);

    /**
     * 获取设备列表 如果没有设备，那么就返回NULL
     *
     * @return
     */
    public static List<String> getDevices() {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("adb devices");
            InputStream in = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            List<String> devices = new ArrayList<>();
            int index = 0;
            while ((line = reader.readLine()) != null) {
                if (index < 1 || StringUtils.isEmpty(line)) {
                    index++;
                    continue;
                }
                LOGGER.info("发现设备:{}", line);
                devices.add(line.split("\t")[0]);
                index++;
            }

            if (devices.size() <= 0) {
                LOGGER.warn("没有找到任何设备!");
            }
            return devices.size() > 0 ? devices : null;
        } catch (IOException e) {
            LOGGER.error("获取设备列表失败:", e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return null;
    }


    public static void main(String[] args) {
        try {
            hasEnv("ANDROID_HOME", "%ANDROID_HOME%\\platform-tools", "%ANDROID_HOME%\\tools");

            getDevices();
        } catch (Exception ex) {
            ex.printStackTrace();
            String text = StringUtils.isEmpty(ex.getMessage()) ? "环境变量配置不完善!" : ex.getMessage();
            new TipWindow("错误", text);
        }
    }
}
